package org.springblade.resource.ueditor.upload;

import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springblade.resource.builder.oss.OssBuilder;
import org.springblade.resource.ueditor.define.BaseState;
import org.springblade.resource.ueditor.define.State;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class Uploader {
	private OssBuilder ossBuilder = null;
	private HttpServletRequest request = null;
	private Map<String, Object> conf = null;

	public Uploader(HttpServletRequest request, Map<String, Object> conf, OssBuilder ossBuilder) {
		this.request = request;
		this.conf = conf;
		this.ossBuilder = ossBuilder;
	}

	public final State doExec() {
		//String filedName = (String) this.conf.get("fieldName");
		State state = null;

		if ("true".equals(this.conf.get("isBase64"))) {
			//state = Base64Uploader.save(this.request.getParameter(filedName), this.conf);
		} else {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
			BladeFile bladeFile = null;
			try {
				bladeFile = ossBuilder.template().putFile(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			//state = BinaryUploader.save(this.request, this.conf);
			if (ObjectUtil.isNotEmpty(bladeFile)) {
				state = new BaseState(true);
				//获取yml配置访问路径前缀
				state.putInfo("url", bladeFile.getLink());
			}
		}
		return state;
	}
}
